const async = require('async');
module.exports = {
  open:false,
  description:'获取评论',
  handler(req,res,next){
    let doc = req.query;
    let filter = doc.filter||{};
    var page = doc.page;
    let sort = doc.sort||{createTime:-1};
    let skip = 0;
    let limit = 10;
    if(page){
      if(page.size){
        limit = page.size;
        if(page.index>1){
          skip = (page.index-1)*page.size;
        }
      }
    }
    async.auto([
      callback=>req.mongo.collection("comment").aggregate([
        {$match:filter},
        {
          $lookup:{
            from:"reply",
            localField:"replyID",
            foreignField:"_id",
            as:"reply"
          }
        },
        {
          $lookup:{
            from:"card",
            localField:"cardID",
            foreignField:"_id",
            as:"cardTitle"
          }
        },
        {$sort:sort},
        {$skip:skip},
        {$limit:limit}
      ]).toArray(callback)
    ],
      (err, results) => {
        if (err) return res.err.mongoError(err);
        const comment = results[0]||[];
        if (!page) {
          // return res.reply(comment);
          return res.reply({code:0,message:"查询成功",data:comment});
        }
        var q = req.mongo.collection("comment").find(filter);
        if (sort)q = q.sort(sort);
        q.count(function (err, count) {
          if (err) return res.err.mongoError(err);
          page.size = page.size || 10;
          page.index = page.index || 1;
          page.count = count;
          page.pageCount = Math.ceil(page.count / page.size);
          if(count<=0) return  res.reply({code:0,message:"查询成功",data:page});
          page.hasPrevious = page.index > 1;
          page.hasNext = page.index < page.pageCount;
          page.index = page.pageCount < page.index ? page.pageCount : page.index;
          page.items = comment;
          return res.reply({code:0,message:"查询成功",data:page});
        });
      }
    )
  }
};

